<template>
  <div>
    <!-- <div class="breadcrumb" style="height: 20px;">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item><a href="/">活动管理</a></el-breadcrumb-item>
                <el-breadcrumb-item>活动列表</el-breadcrumb-item>
                <el-breadcrumb-item>活动详情</el-breadcrumb-item>
            </el-breadcrumb>
        </div> -->
    <div class="breadcrumb" style="height: 20px;">
      <el-breadcrumb separator="/">
        <!-- <el-breadcrumb-item v-for="(breadcrumb, index) in breadcrumbs" :key="index" :to="{ path: breadcrumb.path }">
          <span v-if="breadcrumb.to">{{ breadcrumb.label }}</span>
          <a v-else>{{ breadcrumb.label }}</a>
        </el-breadcrumb-item> -->
        <el-breadcrumb-item v-for="(breadcrumb, index) in breadcrumbs" :key="index">
          <router-link :to="breadcrumb.to">{{ breadcrumb.label }}</router-link>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="icons">
      <!-- <el-avatar shape="square" size="small" :src="squareUrl"></el-avatar> -->
      <el-dropdown placement="bottom-end" @command="handleCommand">
        <span class="el-dropdown__box">
          <el-avatar :src="squareUrl" shape="square" :size="25" style="border: 1px solid #808080;"/>
          <el-icon>
            <CaretBottom />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="updateInfo" :icon="Crop">修改资料</el-dropdown-item>
            <el-dropdown-item command="updatePwd" :icon="EditPen">修改密码</el-dropdown-item>
            <el-dropdown-item command="personInfo" :icon="User">个人信息</el-dropdown-item>
            <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="tabs">
      <el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit" style="height:40px">
        <el-tab-pane :key="item.name" v-for="(item) in editableTabs" :label="item.title" :name="item.name">
          <div v-if="editIndex !== item.name">
            <!-- <span>{{ item.title }}</span> -->
            <!-- <button @click="editTab(item)">修改标签页名称</button> -->
            <el-button type="primary" plain @click="editTab(item)">修改标签页名称</el-button>
          </div>
          <div v-else>
            <!-- <input type="text" v-model="tempTitle" placeholder="Edit tab title" /> -->
            <el-input placeholder="请输入标签页名称" v-model="tempTitle" clearable style="width: 202px;"></el-input>
            <!-- <button @click="saveTabTitle(item.name)">修改</button>
            <button @click="cancelEdit">取消</button> -->

            <el-button type="primary" plain @click="saveTabTitle(item.name)"
              style="width: 95px; margin-left: 10px;">修改</el-button>
            <el-button type="info" plain @click="cancelEdit" style="width: 95px;">取消</el-button>

          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 用户信息展示 -->
    <el-dialog v-model="showUserInfoDialog" title="个人信息" width="20%">
      <div style="text-align: center;">
        <el-avatar :src="personInfoContent.imageURL" size="large" />
        <div style="margin-top: 20px; width: 100%;">
          <div class="info-row">
            <strong class="label">用户名称:</strong>
            <span class="value">{{ personInfoContent.name }}</span>

          </div>

          <div class="info-row">
            <strong class="label">手机号码:</strong>
            <span class="value">{{ personInfoContent.tel }}</span>
          </div>
          <div class="info-row">
            <strong class="label">用户邮箱:</strong>
            <span class="value">{{ personInfoContent.email }}</span>
          </div>
          <div class="info-row">
            <strong class="label">所属部门:</strong>
            <span class="value">{{ personInfoContent.departmentId }}</span>
          </div>
          <div class="info-row">
            <strong class="label">所属角色:</strong>
            <span class="value">{{ roleDescription }}</span>
          </div>
          <div class="info-row">
            <strong class="label">创建日期:</strong>
            <span class="value">{{ personInfoContent.createTime }}</span>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showUserInfoDialog = false" style="margin-left: 180px;">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改密码对话框 -->
    <el-dialog v-model="showChangePasswordDialog" title="修改密码" width="30%">
      <div style="padding: 20px;">
        <!-- 原密码输入框 -->
        <el-form-item label="原密码">
          <el-input v-model="passwords.oldPassword" type="password" placeholder="请输入原密码"
            autocomplete="current-password">
          </el-input>
        </el-form-item>
        <!-- 新密码输入框 -->
        <el-form-item label="新密码">
          <el-input v-model="passwords.newPassword" type="password" placeholder="请输入新密码" autocomplete="new-password">
          </el-input>
        </el-form-item>
        <!-- 确认新密码输入框 -->
        <el-form-item label="确认新密码">
          <el-input v-model="passwords.confirmPassword" type="password" placeholder="请再次输入新密码"
            autocomplete="new-password">
          </el-input>
        </el-form-item>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showChangePasswordDialog = false"  style="margin-left: 230px;">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog v-model="showEditUserDialog" title="修改用户信息" width="30%" v-if="userInfo1">
    <el-form>
      <el-form-item label="用户昵称">
        <el-input v-model="userInfo1.nickname" placeholder="请输入用户昵称"></el-input>
      </el-form-item>
      <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;邮箱">
        <el-input v-model="userInfo1.email" type="email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="userInfo1.tel" type="tel" placeholder="请输入电话号码"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="userInfo1.gender">
          <el-radio :label="true">男</el-radio>
          <el-radio :label="false">女</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showEditUserDialog = false"  style="margin-left: 230px;">取消</el-button>
      <el-button type="primary" @click="handleSubmit1">确定</el-button>
    </span>
  </el-dialog>
  </div>

</template>

<script setup lang="ts">
import { ref, computed, watch,Ref } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox, ElAvatar, ElDialog, ElButton, ElInput, ElRadioGroup, ElRadio } from 'element-plus';
import router from '../../router';
import { SwitchButton, CaretBottom, User, Crop, EditPen } from '@element-plus/icons-vue';
import request from '../../until/request.ts';


const editableTabsValue = ref('1');
const editableTabs = ref([
  { title: 'Tab 1', name: '1', content: "HomeBody", routePath: "/home" }
]);
const tabIndex = ref(1);

const handleTabsEdit = (targetName: any, action: any) => {
  if (action === 'add') {
    const newTabName = `${++tabIndex.value}`;
    editableTabs.value.push({
      title: 'Tab' + newTabName,
      name: newTabName,
      content: 'New Tab content',
      routePath: "/home"
    });
    editableTabsValue.value = newTabName;
  }
  if (action === 'remove') {
    if (editableTabs.value.length === 1) {
      // 禁止删除最后一个标签页
      ElMessage({
        message: "至少保留一个标签页",
        type: 'error',
      });
      return;
    }

    const tabs = editableTabs.value;
    let activeName = editableTabsValue.value;

    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.name;
          }
        }
      });
    }

    editableTabsValue.value = activeName;
    editableTabs.value = tabs.filter(tab => tab.name !== targetName);
  }
};

// 获取当前路由
const route = useRoute();
// 动态生成面包屑
const breadcrumbs = computed(() => {
  const paths = route.path.split('/').filter(Boolean);
  const breadcrumbList = paths.map((path, index) => {
    const to = '/' + paths.slice(0, index + 1).join('/');
    return { label: path, to: to };
  }).slice(1); // 去掉第一个元素

  const activeTab = editableTabs.value.find(tab => tab.name === editableTabsValue.value);
  // return [{ label: '首页', to: '/home' }, { label: activeTab?.title, to: '/home'}, ...breadcrumbList];
  // return [{ label: '首页', to: '/home' }, ...breadcrumbList];
  return [{ label: '首页', to: '/home' }, ...breadcrumbList, { label: '', to: '/home' }];
});

//tab名修改
// 临时变量和编辑状态
const tempTitle = ref('');
const editIndex = ref<string | null>(null);
// 进入编辑模式
const editTab = (item: any) => {
  tempTitle.value = item.title;
  editIndex.value = item.name;
};
// 保存标签名称
const saveTabTitle = (name: string) => {
  const tab = editableTabs.value.find(tab => tab.name === name);
  if (tab) {
    tab.title = tempTitle.value;
  }
  editIndex.value = null;
};
// 取消编辑
const cancelEdit = () => {
  editIndex.value = null;
};


//假tab模仿
// 监听标签页切换事件
watch(editableTabsValue, (newValue, oldValue) => {
  const activeTab = editableTabs.value.find(tab => tab.name === newValue);
  if (activeTab) {
    console.log('切换到标签页：', activeTab.title, '路径:', activeTab.routePath);
    router.push(activeTab.routePath);
  }
});
// 监听路由变化
router.beforeEach((to, from, next) => {
  const activeTab = editableTabs.value.find(tab => tab.name === editableTabsValue.value);
  if (activeTab) {
    activeTab.routePath = to.fullPath;
    activeTab.title = to.fullPath.split('/').filter(Boolean).slice(-1)[0];
  }
  next();
});
import { useUserInfoStore, type UserInfo } from '../../store/userInfo.ts'
const userInfoStore = useUserInfoStore()
import { useTokenStore } from '../../store/token.ts'
const tokenStore = useTokenStore()
import { useRouter } from 'vue-router';
let router1 = useRouter()
import { type UserItem } from '../../api/userApi.ts'
const personInfoContent= ref<UserItem>();
const showUserInfoDialog = ref(false);
//头像
//const squareUrl = 'https://measurement-alliance-collection.oss-cn-beijing.aliyuncs.com/2024-07/44cf37be-8850-406c-b9c7-f61680b3aea7.jpg'

// 定义一个枚举来管理命令类型，以增强代码的可读性和易维护性
enum Command {
  PersonInfo = 'personInfo',
  Logout = 'logout',
  UpdateInfo = 'updateInfo',
  UpdatePwd = 'updatePwd'
}
const handleCommand = async (command: Command) => {
  switch (command) {
    case Command.PersonInfo:
      await handlePersonInfo();
      break;
    case Command.Logout:
      await handleLogout();
      break;
    case Command.UpdateInfo:
      await handleUpdateInfo();
      break;
    case Command.UpdatePwd:
      await handleUpdatePwd();
      break;

  }
};

// 处理获取个人信息的逻辑
const fetchUserInfo = async () => {
  const response = await request.get('/user/getCurrUser');
  return response.data.data;
};
const squareUrl= ref('');
// 获取用户信息
const getUserInfo = async () => {
  try {
    const userInfo = await fetchUserInfo();
    personInfoContent.value = userInfo;
    squareUrl.value = userInfo.imageURL;
    if(squareUrl.value==''){
      squareUrl.value = 'https://measurement-alliance-collection.oss-cn-beijing.aliyuncs.com/2024-07/44cf37be-8850-406c-b9c7-f61680b3aea7.jpg'
    }
  } catch (error) {
    console.error('Failed to fetch user info:', error);
  }
};
getUserInfo();
const handlePersonInfo = async () => {
  const userInfo = await fetchUserInfo();
  personInfoContent.value = userInfo;
  showUserInfoDialog.value = true;
  if(personInfoContent.value.imageURL==''){
    personInfoContent.value.imageURL = 'https://measurement-alliance-collection.oss-cn-beijing.aliyuncs.com/2024-07/44cf37be-8850-406c-b9c7-f61680b3aea7.jpg'
  }
};
// 角色描述的计算属性
const roleDescription = computed(() => {
  switch (personInfoContent.value.role) {
    case '0':
      return '超级管理员';
    case '1':
      return '租户管理员';
    case '2':
      return '普通用户';
    default:
      return '未知角色';
  }
});
// 控制修改密码对话框的显示
const showChangePasswordDialog = ref(false);
const personInfoPwd = ref<UserItem>();
// 存储密码输入
const passwords = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const rightPwd = ref('');
const getPassword = async () => {
  try {
    const res = await fetchUserInfo();
    personInfoPwd.value = res;
    rightPwd.value = personInfoPwd.value.pwd;
  } catch (error) {
    console.error('Failed to fetch user info:', error);
  }
}

console.log(rightPwd);
// 提交密码修改的处理函数
const handleSubmit = async () => {
  await getPassword();
  if (!passwords.value.oldPassword || !passwords.value.newPassword || !passwords.value.confirmPassword) {
    ElMessage.error('密码不能为空');
    return;
  }
  if (passwords.value.oldPassword != rightPwd.value) {
    ElMessage.error('原密码输入错误');
    return;
  }
  if (passwords.value.newPassword !== passwords.value.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致');
    return;
  }
  // 这里添加发送密码到后端的逻辑

  personInfoPwd.value.pwd = passwords.value.newPassword;
  const response = await request.post('/user/passwordEditor', personInfoPwd.value);

  if (response.data.isOk == true) {
    // 假设提交成功后关闭对话框
    showChangePasswordDialog.value = false;
    const response1 = await request.post('/user/logout');
    if (response1.data.code === 0) {
      //清空用户信息，和token
      tokenStore.removeToken();
      userInfoStore.removeInfo();
      //跳转到登录页面
      setTimeout(() => {
        ElMessage.warning('修改密码成功，请重新登录！');
        router1.push('/')
      }, 1000);
    }
  }
};
const handleUpdatePwd = async () => {
  showChangePasswordDialog.value = true;
};
const showEditUserDialog = ref(false);
const userInfo1 = ref<UserItem>();

const handleSubmit1 = async() => {
  
  const response = await request.post('/user/passwordEditor', userInfo1.value);
  if (response.data.isOk == true) {
    // 假设提交成功后关闭对话框
    showEditUserDialog.value = false;
    ElMessage.success('修改用户信息成功');
  }else{
    ElMessage.error('修改用户信息失败');
  }

};
const handleUpdateInfo = async () => {
  showEditUserDialog.value = true;
  const res = await fetchUserInfo();
  userInfo1.value = res;
};
// 处理用户退出登录的逻辑
async function handleLogout() {
  try {
    const confirmation = await ElMessageBox.confirm(
      '你确认退出登录吗？',
      '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
    );
    // 用户确认退出
    const response = await request.post('/user/logout');
    if (response.data.code === 0) {
      tokenStore.removeToken();      // 清空token
      userInfoStore.removeInfo();    // 清空用户信息
      ElMessage.success('退出登录成功');
      router1.push('/');              // 跳转到登录页面
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作
      ElMessage({
        type: 'info',
        message: '已撤销该操作'
      });
    } else {
      console.error('Error during logout:', error);
      ElMessage.error('退出登录失败');
    }
  }
}
</script>

<style>
.breadcrumb {
  display: inline-block;
  padding: 10px 0 0 10px;
}

.breadcrumb el-breadcrumb-item {
  font-weight: 700;
}

.icons {
  display: inline;
  float: right;
  padding: 5px 50px 0 0;
  align-items: center;
}

.tabs {
  height: 40px;
  width: 100%;
}

.el-dropdown__box {
  display: flex;
  align-items: center;

  .el-icon {
    color: #999;
    margin-left: 10px;
  }

  &:active,
  &:focus {
    outline: none;
  }
}

.el-avatar {
  border-radius: 50%;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.label {
  flex: 0 0 30%;
  /* Label width */
  text-align: left;
}

.value {
  flex: 1;
  text-align: right;
  /* Align the content to the right */
}
</style>